package com.oe.user.controller;

import com.oe.common.build.ResponseBuilder;
import com.oe.common.resp.LdmResponse;
import com.oe.user.dao.LagouTokenDao;
import com.oe.user.pojo.LagouToken;
import com.oe.user.service.LdmCodeClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    LagouTokenDao lagouTokenDao;

    @Autowired
    LdmCodeClient ldmCodeClient;


    @RequestMapping("/user/register/{email}/{password}/{code}")
    public LdmResponse register(@PathVariable("email") String email,@PathVariable("password") String password,@PathVariable("code") String code){
        LdmResponse ldmResponse = ldmCodeClient.checkCode(email, code);
        if (!ldmResponse.isSuccess()){
            return ldmResponse;
        }
        LagouToken lagouAuthCode = new LagouToken();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setToken(email+password);
        lagouTokenDao.save(lagouAuthCode);
        return ResponseBuilder.buildResponse(true,"注册成功！",lagouAuthCode);
    };

    @RequestMapping("/user/login/{email}/{password}")
    public LdmResponse login(@PathVariable("email") String email,@PathVariable("password") String password){
        LagouToken lagouAuthCode = lagouTokenDao.findByTokenEquals(email + password);
        if(lagouAuthCode==null){
            return ResponseBuilder.buildResponse(false,"账号或密码不正确！",null);
        }
        return ResponseBuilder.buildResponse(true,"登陆成功！",lagouAuthCode);
    };

    @RequestMapping("/user/isRegistered/{email}")
    public LdmResponse isRegistered(@PathVariable("email") String email){
        LagouToken lagouAuthCode = lagouTokenDao.findByEmailEquals(email);
        if(lagouAuthCode==null){
            return ResponseBuilder.buildResponse(false,"当前用户已注册!",null);
        }
        return ResponseBuilder.buildResponse(true,"当前用户未注册!",null);
    };

    @RequestMapping("/user/info/{token}")
    public LdmResponse getUserInfo(@PathVariable("token") String token){
        LagouToken lagouAuthCode = lagouTokenDao.findByTokenEquals(token);
        if(lagouAuthCode==null){
            return ResponseBuilder.buildResponse(false,"当前token的用户不存在!!!",null);
        }
        return ResponseBuilder.buildResponse(true,null,lagouAuthCode.getEmail());
    };
}
